package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("role")
public class RoleController {

    @Reference
    RoleService roleService;

    @RequestMapping("findAll")
    public Result findAll(){
        try {
            List<Role> roleList=roleService.findAll();
            return new Result(true,"查询角色信息成功",roleList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询角色信息失败");
        }
    }





	@RequestMapping("findPage")
	public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
		return roleService.findPage(queryPageBean);
	}

	@RequestMapping("add")
	public Result addRole(Integer[] permissionIds, Integer[] menuIds, @RequestBody Role role){
		try {
			roleService.add(permissionIds,role,menuIds);
			//维护角色菜单表

			return new Result(true, "添加角色成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "添加角色失败");
		}
	}

	@RequestMapping("delete")
	public Result deleteById(Integer id){
		try {
			roleService.delRoleById(id);
			return new Result(true, "删除角色成功！");
		} catch (RuntimeException e) {
			e.printStackTrace();
			return new Result(false, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "系统出现异常，请稍后再试");
		}
	}

	@RequestMapping("edit")
	public Result editRole(Integer[] permissionIds,Integer[] menuIds,@RequestBody Role role){
		try {
			roleService.editRole(permissionIds, role,menuIds);
			return new Result(true,"修改角色信息成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false,"修改角色信息失败");
		}

	}

	@RequestMapping("findById")
	public Result findById(Integer id){
		try {
			Role role = roleService.findById(id);
			return new Result(true, "查询角色成功", role);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(true, "查询角色失败");
		}
	}

	@RequestMapping("findPermissionIdsByRoleId")
	public Result findPermissionIdsByRoleId(Integer id){
		try {
			List<Integer> permissionIds = roleService.findPermissionIdsByRoleId(id);
			return new Result(true, "查询当前角色权限成功",permissionIds);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(true, "查询当前角色权限失败");
		}
	}
}
